import urllib.request
import xml.dom.minidom
import os
import time
import sqlite3

import utils
import database
import pkcrypt

cats = {"Audio / Music": "AudioMusic",
        "Audio / Audio books": "AudioAudiobooks",
        "Audio / Sound clips": "AudioSoundclips",
        "Audio / FLAC": "AudioFlac",
        "Audio / Other": "AudioOther",
        "Video / Movies": "VideoMovies",
        "Video / Movies DVDR": "VideoMoviesdvdr",
        "Video / Music videos": "VideoMusicvideos",
        "Video / Movie clips": "VideoMovieclips",
        "Video / TV shows": "VideoTvshows",
        "Video / Handheld": "VideoHandheld",
        "Video / Highres - Movies": "VideoHighresmovies",
        "Video / Highres - TV shows": "VideoHighrestvshows",
        "Video / Other": "VideoOther",
        "Applications / Windows": "ApplicationsWindows",
        "Applications / Mac": "ApplicationsMac",
        "Applications / UNIX": "ApplicationsUnix",
        "Applications / Handheld": "ApplicationsHandheld",
        "Applications / Other OS": "ApplicationsOther",
        "Games / PC": "GamesPc",
        "Games / Mac": "GamesMac",
        "Games / PS2": "GamesPs2",
        "Games / XBOX360": "GamesXbox360",
        "Games / Wii": "GamesWii",
        "Games / Handheld": "GamesHandheld",
        "Games / Other": "GamesOther",
        "Porn / Movies": "PornMovies",
        "Porn / Movies DVDR": "PornMoviedvdr",
        "Porn / Pictures": "PornPictures",
        "Porn / Games": "PornGames",
        "Porn / HighRes - Movies": "PornHighresmovies",
        "Porn / Movie clips": "PornMovieclips",
        "Porn / Other": "PornOther",
        "Other / E-books": "OtherEbooks",
        "Other / Comics": "OtherComics",
        "Other / Pictures": "OtherPictures",
        "Other / Covers": "OtherCovers",
        "Other / Other": "OtherOther"}

rssurl = "http://rss.thepiratebay.org/0"

def get_keypair_database():
    newdb = False
    if not os.access("keypairdatabase", os.R_OK):
        newdb = True

    db = sqlite3.connect("keypairdatabase")
    db.isolation_level = None
    if newdb:
        create_keypair_database(db)
    return db

def create_keypair_database(keydb):
    keydb.execute("CREATE TABLE keys ("+
                  "id INTEGER PRIMARY KEY, "+
                  "name TEXT UNIQUE, "+
                  "keypair BLOB)")

def update(db, keydb):
    if os.access("downloadtpb.lasturl", os.R_OK):
        f = open("downloadtpb.lasturl", "rb")
        lasturl = f.read().decode("utf-8")
        f.close()
    else:
        lasturl = ""
    
    root = xml.dom.minidom.parse(urllib.request.urlopen(rssurl))
    channel = root.getElementsByTagName("channel")[0]
    newlasturl = None
    for item in channel.getElementsByTagName("item"):
        title = item.getElementsByTagName("title")[0].childNodes[0].data
        url = item.getElementsByTagName("comments")[0].childNodes[0].data
        pubdate = item.getElementsByTagName("pubDate")[0].childNodes[0].data
        cat = item.getElementsByTagName("category")[0].childNodes[0].data 
        creator = item.getElementsByTagName("dc:creator")[0].childNodes[0].data
        torrent = item.getElementsByTagName("torrent")[0]
        size = torrent.getElementsByTagName("contentLength")[0].childNodes[0].data
        magnet = torrent.getElementsByTagName("magnetURI")[0].childNodes[0].data
        
        print(title)
        
        if url == lasturl:
            break
        
        if not newlasturl:
            newlasturl = url
        
        keydb.execute("BEGIN IMMEDIATE")
        has_key, = keydb.execute("SELECT COUNT(*) "+
                               "FROM keys WHERE name=?", (creator,)).fetchone()
        if has_key == 1:
            keypair, = keydb.execute("SELECT keypair FROM keys "+
                                     "WHERE name=?", (creator,)).fetchone()
            keypair = utils.unserialize_key_pair(keypair)
        else:
            keypair = pkcrypt.generate_key_pair(creator)
            keydb.execute("INSERT INTO keys (name, keypair) VALUES (?, ?)",
                          (creator, utils.serialize_key_pair(keypair)))
        keydb.commit()
        
        text = "Automatically created from TPB feed.\n"+url
        now = int(time.mktime(time.gmtime()))
        my_cat = utils.categories[cats[cat]]
        entry = utils.generate_entry(magnet, title, my_cat, int(size), 
                                     0, now, text, 
                                     keypair)
        utils.insert_entry(db, entry)
        
    
    if newlasturl:
        f = open("downloadtpb.lasturl", "wb")
        lasturl = f.write(newlasturl.encode("utf-8"))
        f.close()
keydb = get_keypair_database()
db = database.get()
while True:
    update(db, keydb)
    time.sleep(30)
db.close()
keydb.close()